﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RabbitMQ.Client;

namespace ConsoleAppFramework.Rmq
{
    public class RmqHttpApiService
    {
        private static string userName;

        private static string password;

        private static string host;

        private static string vhost;

        public RmqHttpApiService(RmqUrlEnum uriEnum, int port = 15672)
        {
            ConnectionFactory innerFactoryObject = RmqConnectPoolFactory.GetClientPool(uriEnum).GetInnerFactoryObject();
            userName = innerFactoryObject.UserName;
            password = innerFactoryObject.Password;
            host = innerFactoryObject.HostName + ":" + port;
            vhost = innerFactoryObject.VirtualHost;
        }

        public string GetNodesDetail()
        {
            return JArray.Parse(GetData($"http://{host}/api/nodes", "get", string.Empty))[0].ToString();
        }

        public int GetMessageCount(string queueName)
        {
            var totalCount= JObject.Parse(GetData($"http://{host}/api/queues/{vhost}/{queueName}", "get", string.Empty)).GetValue("messages").Value<int>();
            return totalCount;
        }

        public string[] GetQueueMessages(string queueName, int takeCount)
        {
            string requestDatas = JsonConvert.SerializeObject(new Dictionary<string, string>
            {
                { "vhost", vhost },
                { "name", queueName },
                { "requeue", "true" },
                { "encoding", "auto" },
                {
                    "count",
                    takeCount.ToString()
                }
            });
            return (from m in JArray.Parse(GetData($"http://{host}/api/queues/{vhost}/{queueName}", "post", requestDatas))
                    select m.SelectToken("payload")!.ToString()).ToArray();
        }

        public static string GetData(string url, string httpMethod, string requestDatas)
        {
            HttpWebRequest httpWebRequest = createRequest(url, requestDatas, httpMethod);
            using HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using Stream stream = httpWebResponse.GetResponseStream();
            return new StreamReader(stream, Encoding.UTF8).ReadToEnd();
        }

        private static HttpWebRequest createRequest(string url, string requestDatas, string httpMethod)
        {
            HttpWebRequest httpWebRequest = ((!(httpMethod.ToLower() == "post")) ? ((HttpWebRequest)WebRequest.Create(url + ((requestDatas == "") ? "" : "?") + requestDatas)) : ((HttpWebRequest)WebRequest.Create(url)));
            httpWebRequest.Method = httpMethod;
            httpWebRequest.Credentials = new NetworkCredential(userName, password);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Timeout = 3000;
            if (httpMethod.ToLower() == "post")
            {
                byte[] bytes = Encoding.UTF8.GetBytes(requestDatas);
                httpWebRequest.ContentLength = bytes.Length;
                using Stream stream = httpWebRequest.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);
                return httpWebRequest;
            }

            return httpWebRequest;
        }
    }
}
